package baiqitun.stupro.common.config;

import baiqitun.stupro.common.constant.SysConstant;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * Mybatis Plus 配置
 * @author kedaji
 */
@Configuration
public class MyBatisPlusConfig {

    /**
     * 字段自动填充
     * @return MetaObjectHandler 实例
     */
    @Bean
    MetaObjectHandler metaObjectHandler(){
        return new MetaObjectHandler(){
            @Override
            public void insertFill(MetaObject metaObject) {
                this.setFieldValByName("id", IdUtil.fastUUID(), metaObject);
                this.setFieldValByName("deleted", "0", metaObject);
                this.setFieldValByName("createDateTime", LocalDateTime.now(), metaObject);
                this.setFieldValByName("sortId",IdUtil.createSnowflake(SysConstant.SNOWFLAKE_WORKER_ID,SysConstant.SNOWFLAKE_DATA_CENTER_ID).nextId(), metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateDateTime", LocalDateTime.now(), metaObject);
            }
        };
    }

    /**
     * 分页插件
     * @return PaginationInterceptor 实例
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
